/// <reference path="../../../../node_modules/@types/crypto-js/index.d.ts" />
import {AfterViewInit, Component, OnDestroy, OnInit} from '@angular/core';
import * as CryptoJS from 'crypto-js';
import {Router} from '@angular/router';
import {UserService} from '../../services/api/user.service';
import {MessageService, ServerConfigService} from '../../../ng-tools';
import {Subscription, timer} from 'rxjs';
import {ThemeService} from '../../services/theme.service';
import {PlatformLocation} from '@angular/common';
import {configFilePath} from '../../app.module';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit, AfterViewInit, OnDestroy {

  sub: Subscription = new Subscription();
  errorMessage: string;
  showMessage = false;

  constructor(private user: UserService,
              private router: Router,
              public theme: ThemeService,
              private serverConfig: ServerConfigService,
              private location: PlatformLocation,
              private message: MessageService) {
  }

  ngOnInit() {
      this.serverConfig.configObserver().subscribe(() => {
          for (const i in this.location) {
              if (i === 'location') {
                  console.log(this.location[i].host);
                  let host = [];
                if (this.location[i].host.indexOf(':') !== -1) {
                  host = this.location[i].host.split(':');
                } else {
                  host = [this.location[i].host, '80'];
                }
                  localStorage.setItem('serverIP', host[0]);
                  localStorage.setItem('serverPort', host[1]);
                  this.serverConfig.config.serverHost =  host[0];
                  this.serverConfig.config.serverPort = host[1];
                  this.serverConfig.httpServer = `${this.serverConfig.config.httpProtocol}://${this.serverConfig.config.serverHost}:${this.serverConfig.config.serverPort}/api`;
                  this.serverConfig.webSocketServer = `${this.serverConfig.config.webSocketProtocol}://${this.serverConfig.config.serverHost}:${this.serverConfig.config.serverPort}/websocket`;
              }
          }
      });
  }

  login(loginForm) {
    if (loginForm.valid) {
      const data = Object.assign({}, loginForm.value);
      data.password = CryptoJS.MD5(data.password).toString();
      this.user.login(data).subscribe(res => {
        localStorage.setItem('token', res.body.token);
        this.user.info();
        this.user.myMenuTree();
        this.router.navigate(['main/oplatform']).catch(reason => {
          console.log(reason);
        });
      }, error1 => {
        console.log(error1);
        this.showErrorMessage(error1.error.msg, 2000);
      });
    }
  }

  enter(e, loginForm) {
    if (e.keyCode === 13) {
      this.login(loginForm);
    }
  }

  showErrorMessage(msg: string, time: number = 2000) {
    this.showMessage = true;
    this.errorMessage = msg;
    if (time !== 0) {
      this.hideErrorMessage(time);
    }
  }

  hideErrorMessage(time: number = 0) {
    timer(time).subscribe(() => {
      this.showMessage = false;
      this.errorMessage = null;
    });
  }

  ngAfterViewInit(): void {
    const i = this.message.getMessage('sign out to login', this).subscribe((next) => {
      if (next.data) {
        const msg = `您的账户已在 ${next.data.ip.toString()} 登录`;
        this.showErrorMessage(msg, 0);
      }
    });
    this.sub.add(i);
  }

  ngOnDestroy(): void {
    this.sub.unsubscribe();
  }

}
